package org.paradigmshift.timelapse.serializers

import net.liftweb.json.Serializer
import org.paradigmshift.timelapse.domain.Issue
import net.liftweb.json.Formats
import net.liftweb.json.TypeInfo
import net.liftweb.json.JsonAST.JObject
import net.liftweb.json.JsonAST.JField
import net.liftweb.json.JsonAST.JString
import org.paradigmshift.timelapse.domain.User
import net.liftweb.json.JsonAST.JValue
import net.liftweb.json.JsonAST.JDouble
import net.liftweb.json.JsonAST.JArray

class IssueSerializer extends Serializer[Issue] {
  
  private val Class = classOf[Issue]
  
  def deserialize( implicit format:Formats ) = {
    case ( TypeInfo( Class, _ ), json) => {
      val key = Option( (json \ "key").extract[String] )
      val reporter = Option( new User( (json \ "fields" \ "reporter" \ "name" ).extract[String], ( json \ "fields" \ "reporter" \ "displayName" ).extract[String] ) )
      val assignee = try {
        Option( new User( (json \ "fields" \ "assignee" \ "name" ).extract[String], ( json \ "fields" \ "assignee" \ "displayName" ).extract[String] ) )
      }
      catch {
        case e:Exception => Option( new User( "", "" ) )
      }
      val summary = ( json \ "fields" \ "summary" ).extract[String]
      val description = ( json \ "fields" \ "description" ).extract[String]
      val priority = (json \ "fields" \ "priority" \ "name" ).extract[String]
      
      new Issue( key, reporter, assignee, description, summary, priority )
    }
  }
  
  def serialize( implicit format:Formats ):PartialFunction[Any, JValue] = {
    // TODO i think this is just here to make the compiler happy.  It probably doesnt work.
    case issue:Issue => JArray( JDouble( 0.0 ) :: JDouble( 0.0 ) :: Nil )
  }
}